﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Subgurim.Controles;
using CounterServerModel;
using CounterServerModel.Authentication;
using System.Collections.Generic;

namespace SmartCounters
{
    public partial class FaultStatus : System.Web.UI.Page
	{

		int m_CurrentLoggedOnUserID;
		List<Fault> m_Faults;

		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_UserPageFilter;
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			InformationReader infoProvider = new InformationReader();
			m_CurrentLoggedOnUserID = ((MainTemplate)Master).LoggedInUser.ID;


			if (Request.QueryString["AccountID"] != null)
			{
				int qsAccountID = int.Parse(Request.QueryString["AccountID"]);
				m_Faults = new InformationReader().GetAllOpenFaults(
					((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, qsAccountID);
			}
			else
			{
				m_Faults = new InformationReader().GetAllOpenFaults(
					((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
			}
			
			rpAccountFaultsList.DataSource = m_Faults;
			rpAccountFaultsList.ItemDataBound += new RepeaterItemEventHandler(rpAccountFaultsList_ItemDataBound);
			rpAccountFaultsList.DataBind();
		}

		void rpAccountFaultsList_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			// treat only items ignore all others
			if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
				return;

			Fault fault = e.Item.DataItem as Fault;

			Button btCloseFault = e.Item.FindControl("btCloseFault") as Button;
			Label lblFaultID = e.Item.FindControl("lblFaultID") as Label;
			Label lblFaultDate = e.Item.FindControl("lblFaultDate") as Label;
			Label lblFaultDescription = e.Item.FindControl("lblFaultDescription") as Label;

			lblFaultID.Text = fault.FaultID.ToString();
			lblFaultDate.Text = fault.FaultDate.ToString("dd/MM/yyy");
			lblFaultDescription.Text = fault.Description;
		}

		protected void rpAccountFaultsList_ItemCommand1(object source, RepeaterCommandEventArgs e)
		{
			Label lblFaulID = e.Item.FindControl("lblFaultID") as Label;
			int faultToCloseID = int.Parse(lblFaulID.Text);
			InformationUpdater updateProvider = new InformationUpdater();

			updateProvider.SolveFault(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials,faultToCloseID);
		}
	}
}